//
//  NSDate+Extension.swift
//  weibo
//
//  Created by yanghong on 15/12/16.
//  Copyright © 2015年 杨鸿. All rights reserved.
//

import UIKit

extension NSDate {
    
    class func sinaDate(createStr: String) -> NSDate? {
        
        let dt = NSDateFormatter()
        
        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        dt.locale = NSLocale(localeIdentifier: "en_US")
        
        let creatDate = dt.dateFromString(createStr)
        
        return creatDate
    }
    
    // 返回新浪微博创建字符串
    
    var sinaDateString: String? {
        
        let dt = NSDateFormatter()
        
        dt.locale = NSLocale(localeIdentifier: "en_US")
        
        let calendar = NSCalendar.currentCalendar()
        
        if isThisYear(self) {
            
            dt.dateFormat = "是今年"
            
            if calendar.isDateInToday(self){
                //进入这里表示是今天
                
                let time = -self.timeIntervalSinceNow
                
                if time < 60 {
                    //一分钟之内
                    return "刚刚"
                }else if time < 60 * 60 {
                    //一个小时之内
                    return "\(Int(time) / 60)分钟之前"
                    
                }else{
                    //几个小时前
                    
                    return "\(Int(time) / (60 * 60) )小时之前"
                }
                
            }else if calendar.isDateInYesterday(self) {
                //进入这里表示是昨天
                dt.dateFormat = "昨天 HH:mm"
                
            }else{
                
                //其他
                
                dt.dateFormat = "MM-dd HH:mm"
            }
            
        }else{
            
            dt.dateFormat = "yyyy-MM-dd HH:mm"
            
        }
        
        return dt.stringFromDate(self)
    }
    
    private func isThisYear(date: NSDate) -> Bool {
        
        let currentDate = NSDate()
        
        let dt = NSDateFormatter()
        
        dt.dateFormat = "yyyy"
        
        dt.locale = NSLocale(localeIdentifier: "en_US")
        
        let  dateString = dt.stringFromDate(date)
        
        let currentDateString = dt.stringFromDate(currentDate)
        
        return  (dateString as NSString).isEqualToString(currentDateString)
    }
}
